package com.yc.system.service.impl;

import com.yc.common.core.domain.entity.SysRole;
import com.yc.common.core.domain.entity.SysUser;
import com.yc.common.core.domain.model.RegisterBody;
import com.yc.common.utils.StringUtil;
import com.yc.common.utils.uuid.IdUtil;
import com.yc.system.mapper.SysUserMapper;
import com.yc.system.mapper.SysUserRoleMapper;
import com.yc.system.service.ISysRoleService;
import com.yc.system.service.ISysUserRoleService;
import com.yc.system.service.ISysUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Collections;

@Service("userServiceImpl")
@Primary
public class SysUserServiceImpl implements ISysUserService {

    private static final Logger log = LoggerFactory.getLogger(SysUserServiceImpl.class);

    @Resource
    private SysUserMapper userMapper;

    @Resource(name = "userRoleService")
    private ISysUserRoleService userRoleService;

    @Resource
    private ISysRoleService sysRoleService;

    @Autowired
    private PasswordEncoder passwordEncoder;


    @Override
    public SysUser selectUserByUserName(String userName) {
        return userMapper.selectUserByUserName(userName);
    }

    @Override
    @Transactional
    public boolean addUserInfo(RegisterBody registerBody) {

        long userId = IdUtil.generateLongUUID();

        // 创建用户对象
        SysUser sysUser = SysUser.builder()
                .userId(userId)
                .nickName(registerBody.getNickName())
                .email(registerBody.getEmail())
                .password(passwordEncoder.encode(registerBody.getPassword())) // 加密密码
                .status("0")
                .isDeleted("0")
                .build();

        // 获取默认角色
        SysRole defaultRole = sysRoleService.getDefaultRole();
        sysUser.setRoles(Collections.singletonList(defaultRole));

        // 保存用户角色关联（假设有 user_role 表）
        userRoleService.addUserRole(sysUser.getUserId(), defaultRole.getRoleId());

        // 保存用户信息到数据库并返回结果
        return userMapper.addUserInfo(sysUser);
    }

    @Override
    public String selectNickNameByUserId(Long userId) {
        return userMapper.selectNickNameByUserId(userId);
    }
}
